"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 硬件故障类--CPU
Case Name   : 逻辑解码时主节点CPU占用率100%
Create At   : 2021/07/12
@zou_jialiang0505328126
Description :
    1.设置wal_level = logical
    2.主节点注入CPU占用率100%故障
    3. 创建逻辑复制槽
    4.创建表并插入数据
    5.解码
    6.删除逻辑复制槽
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.成功
    6.成功
History     :
    Modified by wx1115623 2023/2/16:修改注入CPU占用率故障断言信息
"""

import unittest
import os
import time
from yat.test import Node, macro
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Logger import Logger


class CPUOverloadAndRunTPCC(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.primary_root_node = Node(node='PrimaryRoot')
        self.primary_user_node = Node(node='PrimaryDbUser')
        self.com = Common()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.tb_name = "cpu_tb1"
        self.constant = Constant()

        msg = self.primary_sh.executDbSql('show wal_level;')
        self.log.info(msg)
        self.wal_level = msg.splitlines()[-2].strip()

    def test_main(self):
        self.log.info("-------------1.设置wal_level = logical---------------")
        result = self.primary_sh.executeGsguc(
            "set", self.constant.GSGUC_SUCCESS_MSG, "wal_level = logical")
        self.log.info(result)
        self.assertTrue(result)
        result = self.primary_sh.stopDbCluster()
        self.assertTrue(result)
        result = self.primary_sh.startDbCluster()
        self.assertTrue(result)

        self.log.info("--------------2.主节点注入CPU占用率高故障-------------")
        shell_cmd = "cat /proc/cpuinfo |grep 'processor'|wc -l"
        self.log.info(shell_cmd)
        cpu_num = self.primary_root_node.sh(shell_cmd).result()
        self.log.info(cpu_num)
        inject_command = f"rCPU_Overloadau (cpuid1, cpuid2, usage, time) " \
            f"values(0, {int(cpu_num)-1}, 100, 20)"
        result = self.com.cfe_inject(self.primary_root_node, inject_command)
        self.log.info(result)
        flag = self.constant.cfe_inject_rcpu_overloadau_success_msg in result
        if not flag:
            res = self.com.cfe_inject(self.primary_root_node, inject_command)
            self.log.info(res)
            self.assertIn(self.constant.cfe_inject_rcpu_overloadau_success_msg,
                          res.strip())

        self.log.info("---------3 创建逻辑复制槽---------")
        sql = f"SELECT * FROM pg_create_logical_replication_slot " \
            f"('slot1', 'mppdb_decoding');"
        result = self.primary_sh.executDbSql(sql)
        self.log.info(result)
        self.assertIn('1 row', result)

        self.log.info("----------------4.创建表-------------------")
        sql = f"CREATE TABLE {self.tb_name} " \
            f"(W_WAREHOUSE_SK INTEGER NOT NULL, " \
            f"W_WAREHOUSE_ID  VARCHAR(16) NOT NULL, " \
            f"W_WAREHOUSE_NAME  VARCHAR(20) );" \
            f"insert into {self.tb_name} values(2,'aa','bb');"
        result = self.primary_sh.executDbSql(sql)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, result)
        self.assertIn("INSERT", result)

        self.log.info("-------------5. 逻辑解码------------")
        sql = f"SELECT * FROM " \
            f"pg_logical_slot_peek_changes('slot1', NULL, 4096);"
        result = self.primary_sh.executDbSql(sql)
        self.log.info(result)
        self.assertIn('INSERT', result)
        self.assertIn(self.tb_name, result)

        self.log.info("-------------6. 删除逻辑复制槽-----------")
        sql = f"SELECT * FROM pg_drop_replication_slot('slot1');"
        result = self.primary_sh.executDbSql(sql)
        self.log.info(result)
        self.log.info("(1 row)", result)

    def tearDown(self):
        self.log.info("------------------删除表-----------------")
        time.sleep(20)
        sql = f"drop table if exists {self.tb_name} cascade;"
        result = self.primary_sh.executDbSql(sql)
        self.log.info(result)

        self.log.info("-----------------还原参数-------------")
        self.primary_sh.executeGsguc(
            "set", self.constant.GSGUC_SUCCESS_MSG,
            f"wal_level = {self.wal_level}")
        self.primary_sh.stopDbCluster()
        self.primary_sh.startDbCluster()
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
